package org.theSeed.rbacSecurityJwt.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.Getter;
import lombok.Setter;
import org.theSeed.base.exp.BuzExp;
import org.theSeed.base.pojo.sysEnum.SysCode;
import org.theSeed.base.utils.JwtUtil;
import org.theSeed.base.utils.RsaUtil;
import org.theSeed.rbacBaseCommon.pojo.constant.RbacConstant;
import org.theSeed.rbacBaseCommon.pojo.dto.CacheUserInfoDto;
import org.theSeed.redisIntegration.utils.RedisUtil;

import java.security.Key;
import java.time.Duration;

public class LoginUtil {

    @Setter
    @Getter
    private static Key privateKey;

    @Setter
    @Getter
    private static Key publicKey;

    @Setter
    @Getter
    private static Integer expireMinute = 120;

    /**
     * 创建token
     * @param loginInfo
     * @return
     * @param <T>
     */
    public static <T> String createToken(CacheUserInfoDto<T> loginInfo){
        return JwtUtil.generateToken(privateKey, loginInfo.getUserKey(), expireMinute * 60000);
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public static String getUserKey(String token){
        return JwtUtil.parseToken(privateKey,token).getSubject();
    }

    /**
     * 获取登录信息
     * @return
     * @param <T>
     */
    public static <T> T getLoginInfo(String token){
        String userKey = getUserKey(token);
        if (ObjectUtil.isNotEmpty(userKey)){
            return (T)(RedisUtil.getRedissonClient().getBucket(RbacConstant.CACHE_USER_INFO+userKey).get());
        }
        return null;
    }

    /**
     * 登录
     * @param loginInfo
     * @return
     * @param <T>
     */
    public static <T> String login(CacheUserInfoDto<T> loginInfo){
        RedisUtil.getRedissonClient().getBucket(RbacConstant.CACHE_USER_INFO+loginInfo.getUserKey())
                .set(loginInfo, Duration.ofMinutes(expireMinute + 2));
        return createToken(loginInfo);
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    public static void logout(String token){
        RedisUtil.getRedissonClient().getBucket(RbacConstant.CACHE_USER_INFO+getUserKey(token))
                .delete();
    }

    /**
     * 获取token
     * @return
     */
    public static String getToken(String authToken){
        if (ObjectUtil.isNotEmpty(authToken) && authToken.length() > RbacConstant.AUTH_VALUE_PREFIX.length()){
            return authToken.substring(RbacConstant.AUTH_VALUE_PREFIX.length());
        }
        throw new BuzExp(SysCode.PARAM_ERR,"token格式错误");
    }
}
